package hierarchy

import (
	"errors"
	"gitcode.com/G-YT/iHealth25/server/global"
	"gitcode.com/G-YT/iHealth25/server/model/common/request"
	healthReq "gitcode.com/G-YT/iHealth25/server/model/health/request"
	"gitcode.com/G-YT/iHealth25/server/model/hierarchy"
	hierarchyReq "gitcode.com/G-YT/iHealth25/server/model/hierarchy/request"
	hierarchyRes "gitcode.com/G-YT/iHealth25/server/model/hierarchy/response"
	"gorm.io/gorm"
)

type FdArticleLearnService struct {
}

// CreateFdArticleLearn 创建学习文章
// Author [g-qs](https://gitee.com/g-qs)
func (fdArticleLearnService *FdArticleLearnService) CreateFdArticleLearn(fdArticleLearn *hierarchy.FdArticleLearn) (err error) {
	err = global.GVA_DB.Create(fdArticleLearn).Error
	return err
}

// DeleteFdArticleLearn 删除学习文章
// Author [g-qs](https://gitee.com/g-qs)
func (fdArticleLearnService *FdArticleLearnService) DeleteFdArticleLearn(fdArticleLearn hierarchy.FdArticleLearn) (err error) {
	var physique healthReq.PhysiqueArticle
	var solarTerms healthReq.FdJqArticle
	var efficacy healthReq.FdEfficacyArticle
	var disease healthReq.DiseaseArticle
	// 查询是否存在关联体质
	if !errors.Is(global.GVA_DB.Where("article_id = ? AND type = 'video'", fdArticleLearn.ID).Preload("Physique").Preload("FdArticleVideo").First(&physique).Error, gorm.ErrRecordNotFound) {
		return errors.New("请先取消体质管理中【" + physique.Physique.Name + "】与【" + physique.FdArticleVideo.Title + "】的关联关系")
	}
	// 查询是否存在关联节气
	if !errors.Is(global.GVA_DB.Where("article_id = ? AND type = 'video'", fdArticleLearn.ID).Preload("SolarTerms").Preload("FdArticleVideo").First(&solarTerms).Error, gorm.ErrRecordNotFound) {
		return errors.New("请先取消节气管理中【" + solarTerms.SolarTerms.JqName + "】与【" + solarTerms.FdArticleVideo.Title + "】的关联关系")
	}
	// 查询是否存在关联功效
	if !errors.Is(global.GVA_DB.Where("article_id = ? AND type = 'video'", fdArticleLearn.ID).Preload("Efficacy").Preload("FdArticleVideo").First(&efficacy).Error, gorm.ErrRecordNotFound) {
		return errors.New("请先取消功效管理中【" + efficacy.Efficacy.Name + "】与【" + efficacy.FdArticleVideo.Title + "】的关联关系")
	}
	// 查询是否存在关联病症
	if !errors.Is(global.GVA_DB.Where("article_id = ? AND type = 'video'", fdArticleLearn.ID).Preload("Disease", func(db *gorm.DB) *gorm.DB {
		return db.Preload("DiseaseList")
	}).Preload("FdArticleVideo").First(&disease).Error, gorm.ErrRecordNotFound) {
		return errors.New("请先取消病症管理中【" + disease.Disease.DiseaseList.Name + "】下的【" + disease.Disease.Name + "】与【" + disease.FdArticleVideo.Title + "】的关联关系")
	}
	err = global.GVA_DB.Delete(&fdArticleLearn).Error
	return err
}

// DeleteFdArticleLearnByIds 批量删除学习文章
// Author [g-qs](https://gitee.com/g-qs)
func (fdArticleLearnService *FdArticleLearnService) DeleteFdArticleLearnByIds(ids request.IdsReq) (err error) {
	var physique healthReq.PhysiqueArticle
	var solarTerms healthReq.FdJqArticle
	var efficacy healthReq.FdEfficacyArticle
	var disease healthReq.DiseaseArticle
	// 查询是否存在关联体质
	if !errors.Is(global.GVA_DB.Where("article_id in ? AND type = 'video'", ids.Ids).Preload("Physique").Preload("FdArticleVideo").First(&physique).Error, gorm.ErrRecordNotFound) {
		return errors.New("请先取消体质管理中【" + physique.Physique.Name + "】与【" + physique.FdArticleVideo.Title + "】的关联关系")
	}
	// 查询是否存在关联节气
	if !errors.Is(global.GVA_DB.Where("article_id in ? AND type = 'video'", ids.Ids).Preload("SolarTerms").Preload("FdArticleVideo").First(&solarTerms).Error, gorm.ErrRecordNotFound) {
		return errors.New("请先取消节气管理中【" + solarTerms.SolarTerms.JqName + "】与【" + solarTerms.FdArticleVideo.Title + "】的关联关系")
	}
	// 查询是否存在关联功效
	if !errors.Is(global.GVA_DB.Where("article_id in ? AND type = 'video'", ids.Ids).Preload("Efficacy").Preload("FdArticleVideo").First(&efficacy).Error, gorm.ErrRecordNotFound) {
		return errors.New("请先取消功效管理中【" + efficacy.Efficacy.Name + "】与【" + efficacy.FdArticleVideo.Title + "】的关联关系")
	}
	// 查询是否存在关联病症
	if !errors.Is(global.GVA_DB.Where("article_id in ? AND type = 'video'", ids.Ids).Preload("Disease", func(db *gorm.DB) *gorm.DB {
		return db.Preload("DiseaseList")
	}).Preload("FdArticleVideo").First(&disease).Error, gorm.ErrRecordNotFound) {
		return errors.New("请先取消病症管理中【" + disease.Disease.DiseaseList.Name + "】下的【" + disease.Disease.Name + "】与【" + disease.FdArticleVideo.Title + "】的关联关系")
	}
	err = global.GVA_DB.Delete(&[]hierarchy.FdArticleLearn{}, "id in ?", ids.Ids).Error
	return err
}

// UpdateFdArticleLearn 更新学习文章
// Author [g-qs](https://gitee.com/g-qs)
func (fdArticleLearnService *FdArticleLearnService) UpdateFdArticleLearn(fdArticleLearn hierarchy.FdArticleLearn) (err error) {
	//updateFields := map[string]interface{}{
	//	"title":          fdArticleLearn.Title,
	//	"briefly":        fdArticleLearn.Briefly,
	//	"cover":          fdArticleLearn.Cover,
	//	"video_link":     fdArticleLearn.VideoLink,
	//	"image":          fdArticleLearn.Image,
	//	"details":        fdArticleLearn.Details,
	//	"status":         fdArticleLearn.Status,
	//	"is_paid":        fdArticleLearn.IsPaid,
	//	"level_one_id":   fdArticleLearn.LevelOneID,
	//	"level_two_id":   fdArticleLearn.LevelTwoID,
	//	"level_three_id": fdArticleLearn.LevelThreeID,
	//}
	//err = global.GVA_DB.Updates(updateFields).Error
	err = global.GVA_DB.Save(&fdArticleLearn).Error
	return err
}

// GetFdArticleLearn 根据id获取学习文章
// Author [g-qs](https://gitee.com/g-qs)
func (fdArticleLearnService *FdArticleLearnService) GetFdArticleLearn(id uint, userID uint) (fdArticleLearn hierarchy.FdArticleLearn, err error) {
	var collect hierarchy.FdArticleCollect
	var like hierarchy.FdArticleLike
	coErr := global.GVA_DB.Where("fd_article_id = ? and user_id = ? and fd_article_type = ?", id, userID, "learn").First(&collect)
	liErr := global.GVA_DB.Where("fd_article_id = ? and user_id = ? and fd_article_type = ?", id, userID, "learn").First(&like)
	db := global.GVA_DB.Where("id = ?", id).First(&fdArticleLearn)
	err = db.Error
	if coErr.Error != nil {
		fdArticleLearn.IsCollect = false
	} else {
		fdArticleLearn.IsCollect = true
	}
	if liErr.Error != nil {
		fdArticleLearn.IsPraise = false
	} else {
		fdArticleLearn.IsPraise = true
	}
	fdArticleLearn.PV += 1
	db.Update("pv", fdArticleLearn.PV)
	return
}

// GetFdArticleLearnInfoList 分页获取学习文章
// Author [g-qs](https://gitee.com/g-qs)
func (fdArticleLearnService *FdArticleLearnService) GetFdArticleLearnInfoList(info hierarchyReq.FdArticleLearnSearch) (list []hierarchy.FdArticleLearn, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)

	// 创建db
	db := global.GVA_DB.Model(&hierarchy.FdArticleLearn{})
	var fdArticleLearns []hierarchy.FdArticleLearn
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}

	if info.LevelOneID != nil {
		db = db.Where("level_one_id = ?", info.LevelOneID)
	}
	if info.LevelTwoID != nil {
		db = db.Where("level_two_id = ?", info.LevelTwoID)
	}
	if info.LevelThreeID != nil {
		db = db.Where("level_three_id = ?", info.LevelThreeID)
	}
	if info.Title != "" {
		db = db.Where("title LIKE ?", "%"+info.Title+"%")
	}
	if info.IsPaid != nil {
		db = db.Where("is_paid = ?", info.IsPaid)
	}
	if info.Status != nil {
		db = db.Where("status = ?", info.Status)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&fdArticleLearns).Error

	return fdArticleLearns, total, err
}

func (fdArticleLearnService *FdArticleLearnService) FdArticleLike(userID uint, id uint) (fdArticleLearn hierarchy.FdArticleLearn, err error) {
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {

		tdb := tx.Where("id = ?", id).First(&fdArticleLearn)

		uidb := tx.Where("user_id = ? and fd_article_id = ? and fd_article_type = ?", userID, id, "video").First(&hierarchy.FdArticleLike{})

		if errors.Is(uidb.Error, gorm.ErrRecordNotFound) {
			fdArticleLearn.PraiseNum += 1
			uidb = tx.Create(&hierarchy.FdArticleLike{
				UserID:        userID,
				FdArticleID:   id,
				FdArticleType: "video",
			})
			fdArticleLearn.IsPraise = true
		} else {
			fdArticleLearn.PraiseNum -= 1
			uidb = tx.Delete(&hierarchy.FdArticleLike{}, "user_id = ? and fd_article_id = ? and fd_article_type = ?", userID, id, "video")
			fdArticleLearn.IsPraise = false
		}
		return tdb.Update("praise_num", fdArticleLearn.PraiseNum).Error
	})
	return
}

func (fdArticleLearnService *FdArticleLearnService) FdArticleCollect(userID uint, id uint) (fdArticleLearn hierarchy.FdArticleLearn, err error) {
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {

		tdb := tx.Where("id = ?", id).First(&fdArticleLearn)

		uidb := tx.Where("user_id = ? and fd_article_id = ? and fd_article_type = ?", userID, id, "video").First(&hierarchy.FdArticleCollect{})

		if errors.Is(uidb.Error, gorm.ErrRecordNotFound) {
			fdArticleLearn.CollectNum += 1
			uidb = tx.Create(&hierarchy.FdArticleCollect{
				UserID:        userID,
				FdArticleID:   id,
				FdArticleType: "video",
			})
			fdArticleLearn.IsCollect = true
		} else {
			fdArticleLearn.CollectNum -= 1
			uidb = tx.Delete(&hierarchy.FdArticleCollect{}, "user_id = ? and fd_article_id = ? and fd_article_type = ?", userID, id, "video")
			fdArticleLearn.IsCollect = false
		}
		return tdb.Update("collect_num", fdArticleLearn.CollectNum).Error
	})
	return
}

// SetBuyArticle 设置购买学习文章
func (fdArticleLearnService *FdArticleLearnService) SetBuyArticle(req hierarchyReq.BuyArticleReq) (err error) {
	var buyArticle []hierarchy.BuyArticle
	return global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		err = tx.Where("hmID = ?", req.HmID).Delete(&buyArticle).Error
		if err != nil {
			return err
		}
		for _, article := range req.Articles {
			buyArticle = append(buyArticle, hierarchy.BuyArticle{
				HmID:      req.HmID,
				ArticleID: article,
			})
		}
		err = tx.Create(&buyArticle).Error
		return err
	})
}

// GetBuyArticle 获取购买学习文章
func (fdArticleLearnService *FdArticleLearnService) GetBuyArticle(hmID string) (articles []hierarchy.BuyArticle, err error) {
	err = global.GVA_DB.Where("hmID = ?", hmID).Find(&articles).Error
	return
}

// GetLearnLevel 获取学习目录
func (fdArticleLearnService *FdArticleLearnService) GetLearnLevel(levelOneID string) (list []hierarchy.LevelTwo, err error) {
	err = global.GVA_DB.Model(&hierarchy.LevelTwo{}).Preload("LevelThrees").Order("created_at ASC").Where("level_one_id = ?", levelOneID).Find(&list).Error
	return
}

// GetLearnArticleByHmId 根据健管师ID获取学习文章列表
func (fdArticleLearnService *FdArticleLearnService) GetLearnArticleByHmId(hmID uint, levelThreeID string) (list []hierarchyRes.ThreeLevel, err error) {
	var levelThrees []hierarchyRes.ThreeLevel
	db := global.GVA_DB.Model(&hierarchy.LevelThree{}).
		Preload("Articles", func(db *gorm.DB) *gorm.DB {
			return db.Preload("BuyArticle", "hmID = ?", hmID).Order("created_at desc")
		}).Where("id = ?", levelThreeID)
	err = db.Find(&levelThrees).Error
	for i := range levelThrees {
		var articleList []hierarchy.FdArticleLearn
		for i2 := range levelThrees[i].Articles {
			if levelThrees[i].Articles[i2].BuyArticle != nil {
				levelThrees[i].Articles[i2].BuyStatus = true
			} else {
				levelThrees[i].Articles[i2].BuyStatus = false
			}
		}
		articleList = levelThrees[i].Articles
		list = append(list, hierarchyRes.ThreeLevel{
			GVA_MODEL: global.GVA_MODEL{
				ID: levelThrees[i].ID,
			},
			Value:    levelThrees[i].Value,
			Key:      levelThrees[i].Key,
			Articles: articleList,
		})
	}
	return
}
